//导入依耐
const gulp = require("gulp");
const plugins = require("gulp-load-plugins")();
const htmlbeautify = require("gulp-html-beautify"); //html格式化
const babel = require("gulp-babel");
const _ = require("underscore");
const browserSync = require("browser-sync").create();
const reload = browserSync.reload;
//导入配置
const config = require("./config");

let pages = _.compact(
  _.map(config.pages, (page, index) => (!page ? index : false))
);

let src1 = _.map(pages, page => "!./src" + page + "/*.html");
let src2 = _.map(pages, page => "!./src" + page + "/*.scss");
let src3 = _.map(pages, page => "!./src" + page + "/*.js");
let src4 = _.map(pages, page => "!./src" + page + "/img/*.*");

//服务器---------------------------------------------------
gulp.task("go", () => {
  browserSync.init({
    server: {
      baseDir: "./dist"
    },
    directory: true,
    port: 1000,
    ghostMode: {
      clicks: true,
      forms: true,
      scroll: true
    }
  });
  gulp.watch(["./src/**/*.*"], ["html", "scss", "es6"]).on("change", reload);
});
gulp.task("html", () =>
  gulp
    .src(["./src/**/*.html", ...src1])
    .pipe(htmlbeautify({ indentSize: 2 })) //整理格式
    .pipe(gulp.dest("./dist"))
);
gulp.task("scss", () =>
  gulp
    .src(["./src/**/*.scss", ...src2])
    .pipe(plugins.sass().on("error", plugins.sass.logError))
    .pipe(
      plugins.autoprefixer({
        browsers: [
          "last 3 versions",
          "Android >= 4.0",
          "last 3 Explorer versions",
          "opera 15"
        ],
        remove: true
      })
    )
    .pipe(plugins.minifyCss())
    .pipe(gulp.dest("./dist"))
)
gulp.task("es6", () =>
  gulp
    .src(["./src/**/*.js", ...src3])
    .pipe(babel({ presets: ["es2015"] }))
    .pipe(gulp.dest("./dist"))
)
//文件拷贝
gulp.task("file", () =>
  gulp.src(["./src/comm*/**","./src/**/img*/*.*", ...src4]).pipe(gulp.dest("./dist"))
)

//打包
gulp.task("build", ["html", "scss", "es6", "file"]);
